package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.dao.LagouUserDao;
import com.lagou.edu.feign.CodeServiceFeign;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.pojo.LagouUser;
import com.lagou.edu.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

/**
 * @author Administrator
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private LagouTokenDao tokenDao;

    @Autowired
    private LagouUserDao userDao;

    @Autowired
    private CodeServiceFeign codeServiceFeign;

    @Override
    public int register(String email, String password, String code) {
        if (isRegistered(email)) {
            return 1;
        }
        int validate = codeServiceFeign.validate(email, code);
        if (validate != 0) {
            return validate;
        }
        userDao.save(LagouUser.builder().email(email).password(password).build());
        return 0;
    }

    @Override
    public boolean isRegistered(String email) {
        return userDao.findOne(Example.of(LagouUser.builder().email(email).build())).orElse(null) != null;
    }

    @Override
    public LagouToken login(String email, String password) {
        Example<LagouUser> example = Example.of(LagouUser.builder().email(email).password(password).build());
        LagouUser lagouUser = userDao.findOne(example).orElse(null);
        if (lagouUser == null) {
            return null;
        }
        LagouToken lagouToken = LagouToken.builder().email(email).token(UUID.randomUUID().toString()).build();
        tokenDao.save(lagouToken);
        return lagouToken;
    }

    @Override
    public String info(String token) {
        Optional<LagouToken> optional = tokenDao.findOne(Example.of(LagouToken.builder().token(token).build()));
        return optional.map(t -> t.getEmail()).orElse(null);
    }
}
